package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.entity.Secondhand;
import com.campus.help.entity.SecondhandType;
import com.campus.help.exception.BusinessException;
import com.campus.help.mapper.SecondhandMapper;
import com.campus.help.mapper.SecondhandTypeMapper;
import com.campus.help.service.SecondhandService;
import com.campus.help.vo.SecondhandVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 二手商品服务实现类
 *
 * @author campus-help
 * @since 2025-10-16
 */
@Slf4j
@Service
public class SecondhandServiceImpl implements SecondhandService {

    @Autowired
    private SecondhandMapper secondhandMapper;

    @Autowired
    private SecondhandTypeMapper secondhandTypeMapper;

    @Override
    public Page<SecondhandVO> getSecondhandList(
            int page,
            int size,
            String keyword,
            Long typeId,
            String location,
            BigDecimal minPrice,
            BigDecimal maxPrice,
            String condition,
            String status,
            Long schoolId
    ) {
        Page<SecondhandVO> pageParam = new Page<>(page, size);
        
        // 记录学校ID过滤
        if (schoolId != null) {
            log.info("查询二手商品列表，添加学校ID过滤: schoolId={}", schoolId);
        } else {
            log.warn("未提供学校ID，可能导致数据泄露");
        }
        
        return secondhandMapper.selectSecondhandListWithInfo(
                pageParam,
                keyword,
                typeId,
                location,
                minPrice,
                maxPrice,
                condition,
                status,
                schoolId
        );
    }

    @Override
    public SecondhandVO getSecondhandDetail(Long id) {
        SecondhandVO detail = secondhandMapper.selectSecondhandDetailById(id);
        if (detail != null) {
            // 设置状态文本
            detail.setStatusText(getStatusText(detail.getStatus()));
        }
        return detail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Secondhand publishSecondhand(Secondhand secondhand, Long sellerId, Long schoolId) {
        // 设置卖家ID
        secondhand.setSellerId(sellerId);
        
        // 设置学校ID（数据隔离）
        secondhand.setSchoolId(schoolId);
        log.info("设置二手商品学校ID: schoolId={}", schoolId);
        
        // 设置默认值
        if (secondhand.getStatus() == null) {
            secondhand.setStatus("selling");
        }
        if (secondhand.getViewCount() == null) {
            secondhand.setViewCount(0);
        }
        if (secondhand.getFavoriteCount() == null) {
            secondhand.setFavoriteCount(0);
        }
        if (secondhand.getIsUrgent() == null) {
            secondhand.setIsUrgent(0);
        }
        if (secondhand.getFreeShipping() == null) {
            secondhand.setFreeShipping(0);
        }
        if (secondhand.getNegotiable() == null) {
            secondhand.setNegotiable(0);
        }

        // 保存到数据库
        int result = secondhandMapper.insert(secondhand);
        if (result > 0) {
            log.info("发布二手商品成功，ID: {}, schoolId: {}", secondhand.getId(), schoolId);
            return secondhand;
        }
        throw new BusinessException("发布二手商品失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Secondhand updateSecondhand(Secondhand secondhand, Long sellerId) {
        // 验证商品是否存在
        Secondhand existingSecondhand = secondhandMapper.selectById(secondhand.getId());
        if (existingSecondhand == null) {
            throw new BusinessException("商品不存在");
        }

        // 验证是否是卖家本人
        if (!existingSecondhand.getSellerId().equals(sellerId)) {
            throw new BusinessException("无权限修改该商品");
        }

        // 更新商品信息
        int result = secondhandMapper.updateById(secondhand);
        if (result > 0) {
            log.info("更新二手商品成功，ID: {}", secondhand.getId());
            return secondhandMapper.selectById(secondhand.getId());
        }
        throw new BusinessException("更新商品失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSecondhand(Long id, Long sellerId) {
        // 验证商品是否存在
        Secondhand secondhand = secondhandMapper.selectById(id);
        if (secondhand == null) {
            throw new BusinessException("商品不存在");
        }

        // 验证是否是卖家本人
        if (!secondhand.getSellerId().equals(sellerId)) {
            throw new BusinessException("无权限删除该商品");
        }

        // 逻辑删除
        int result = secondhandMapper.deleteById(id);
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean offShelf(Long id, Long sellerId) {
        return updateStatus(id, sellerId, "off_shelf");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean onShelf(Long id, Long sellerId) {
        return updateStatus(id, sellerId, "selling");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsSold(Long id, Long sellerId) {
        return updateStatus(id, sellerId, "sold");
    }

    /**
     * 更新商品状态
     */
    private boolean updateStatus(Long id, Long sellerId, String status) {
        // 验证商品是否存在
        Secondhand secondhand = secondhandMapper.selectById(id);
        if (secondhand == null) {
            throw new BusinessException("商品不存在");
        }

        // 验证是否是卖家本人
        if (!secondhand.getSellerId().equals(sellerId)) {
            throw new BusinessException("无权限操作该商品");
        }

        // 更新状态
        secondhand.setStatus(status);
        int result = secondhandMapper.updateById(secondhand);
        return result > 0;
    }

    @Override
    public void incrementViewCount(Long id) {
        secondhandMapper.incrementViewCount(id);
    }

    @Override
    public void incrementFavoriteCount(Long id) {
        secondhandMapper.incrementFavoriteCount(id);
    }

    @Override
    public void decrementFavoriteCount(Long id) {
        secondhandMapper.decrementFavoriteCount(id);
    }

    @Override
    public Page<Secondhand> getMyPublishedList(Long sellerId, int page, int size) {
        Page<Secondhand> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Secondhand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Secondhand::getSellerId, sellerId)
                .orderByDesc(Secondhand::getCreateTime);
        return secondhandMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public List<SecondhandVO> getHotSecondhandList(int limit) {
        Page<SecondhandVO> pageParam = new Page<>(1, limit);
        Page<SecondhandVO> result = secondhandMapper.selectSecondhandListWithInfo(
                pageParam,
                null,        // keyword
                null,        // typeId
                null,        // location
                null,        // minPrice
                null,        // maxPrice
                null,        // condition
                "selling",   // status
                null         // schoolId - 热门商品不限制学校
        );
        return result.getRecords();
    }

    @Override
    public List<SecondhandType> getAllTypes() {
        LambdaQueryWrapper<SecondhandType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondhandType::getStatus, 1)
                .orderByAsc(SecondhandType::getSortOrder);
        return secondhandTypeMapper.selectList(queryWrapper);
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(String status) {
        switch (status) {
            case "selling":
                return "在售中";
            case "sold":
                return "已售出";
            case "off_shelf":
                return "已下架";
            default:
                return "未知";
        }
    }
}

